package com.example.universitylibraryback.pipeline.filter;

import com.example.universitylibraryback.pipeline.Filter;
import com.example.universitylibraryback.pipeline.ReaderRegistrationContext;
import java.util.concurrent.BlockingQueue;

/**
 * 读者添加解析过滤器
 * 负责解析原始输入为读者信息
 */
public class RequestParserFilter implements Filter<ReaderRegistrationContext>, Runnable {
    private BlockingQueue<ReaderRegistrationContext> inputQueue;
    private BlockingQueue<ReaderRegistrationContext> outputQueue;

    @Override
    public void process(BlockingQueue<ReaderRegistrationContext> inputQueue,
                        BlockingQueue<ReaderRegistrationContext> outputQueue) throws InterruptedException {
        this.inputQueue = inputQueue;
        this.outputQueue = outputQueue;
        new Thread(this).start(); // 启动过滤器线程
    }

    @Override
    public void run() {
        try {
            while (!Thread.currentThread().isInterrupted()) { // 持续处理请求
                ReaderRegistrationContext context = inputQueue.take();
                // 模拟解析逻辑
                String[] parts = context.getRawInput().split(",");
                if (parts.length == 3) {
                    context.setReaderId(parts[0].trim());
                    context.setReaderName(parts[1].trim());
                    context.setEmail(parts[2].trim());
                    context.setMessage("Request parsed successfully");
                } else {
                    context.setValid(false);
                    context.setMessage("Error: Invalid input format. Expected 'id,name,email'");
                }
                outputQueue.put(context); // 将处理后的上下文放入输出队列
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt(); // 恢复中断状态
            System.err.println("RequestParserFilter interrupted.");
        }
    }
}